function Table7

addpath('basic_functions')
addpath('../Data')

Nfactors = 3;

[Return,Z,IsF,Nt,Chars,CharsNames,~,time_end,~] = package_data_all_greeks;
Return = Return.ret_daily;
[N,T,L] = size(Z);

% construct W and X matrices that will be used for IPCA
W = NaN(L,L,T);
X = NaN(L,T);
for t = 1:T-1
    W(:,:,t) = squeeze(Z(IsF(:,t+1),t,:))'*squeeze(Z(IsF(:,t+1),t,:)) / Nt(t+1);
    X(:,t+1) = squeeze(Z(IsF(:,t+1),t,:))'*Return(IsF(:,t+1),t+1) / Nt(t+1);
    Return(~IsF(:,t+1),t+1) = NaN;
end
clear t

% zero alpha
[G, F] = IPCA(X,W,Nt,Nfactors);

dd = csvread('../Data/MacroVars.csv');
[a,b,c] = intersect(dd(:,1),time_end);
dd = dd(b,:);

% 1	            2	        3	      4   5	        6	      7
% exdate	exdatep1	Recession	VIX	MktmRf	KJ_tail	 HKM_ICRac
vix = dd(:,4)/100;
dvix = [NaN; vix(2:end)-vix(1:end-1)];
mkt = dd(:,5);

F = 100*F(:,2:end);
mkt = mkt(2:end);
dvix = dvix(2:end);

% load tail risk
lambda = dd(:,6);
lambda = lambda(2:end);

% intermediary
intf = dd(:,7);
intf = intf(2:end);

% IMF
load('../Data/IMF')
volQ = IMF.RvolP.^2-IMF.volQ.^2;
skewQ = IMF.RskewP-IMF.skewQ;
kurtQ = IMF.RkurtP-IMF.kurtQ;
volQ = volQ(1:end-1);
skewQ = skewQ(1:end-1);
kurtQ = kurtQ(1:end-1);

% average gamma and vega
gamma = squeeze(nanmean(Chars(:,:,6)));
vega = squeeze(nanmean(Chars(:,:,5)));
gamma = gamma(1:end-1);
vega = vega(1:end-1);

var{1,1} = 'Market Ret.';
var{2,1} = '$\Delta$ VIX';

var{3,1} = 'Tail Risk';
var{4,1} = 'Vol Risk';
var{5,1} = 'Skew Risk';
var{6,1} = 'Kurt Risk';

var{7,1} = 'ICRFac';
var{8,1} = 'Average Gamma';
var{9,1} = 'Average Vega';

lb = 50;
ub = 100 - lb;
XX = [];
CC = [];

XX = [-mkt dvix lambda -volQ skewQ -kurtQ -intf gamma' vega']; 

%% construct cases
for i = 1:size(XX,2)
    bb = []; cc=[];
    for j = 1:3
        X = (XX(:,i) - mean(XX(:,i),'omitnan'))./std(XX(:,i),'omitnan');
        ind = X > prctile(X,lb);
        [b1,~,t1] = OLS(F(j,:)',[ones(size(F,2),1) ind],2); %X ind.*X
        for z = 2:length(b1)
            bb = [bb '&' num2str_math(b1(z),'%1.2f')];
            cc = [cc '&(' num2str_math(t1(z),'%1.2f') ')'];
        end
    end
    bb = [bb '&'];
    cc = [cc '&'];
    for j = 1:3
        X = (XX(:,i) - mean(XX(:,i),'omitnan'))./std(XX(:,i),'omitnan');
        ind = X > prctile(X,lb);
        [b1,~,t1] = OLS(F(j,:)',[ones(size(F,2),1) X],2); %X ind.*X
        for z = 2:length(b1)
            bb = [bb '&' num2str_math(b1(z),'%1.2f')];
            cc = [cc '&(' num2str_math(t1(z),'%1.2f') ')'];
        end
    end
    disp([var{i,1} bb '\\'])
    disp([cc '\\'])
end

return